package dht.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Queue;

import dht.entity.NodeInfo;
import dht.throwable.DhtException;

public class SocketListener implements Runnable {
	protected NodeInfo localInfo;
	protected ServerSocket serverSocket;
	protected Queue<SocketHandler> socketQueue;

	public SocketListener(int port, NodeInfo localInfo,
			Queue<SocketHandler> socketQueue) throws DhtException {
		this.localInfo = localInfo;
		this.socketQueue = socketQueue;
		try {
			this.serverSocket = new ServerSocket(port);
		} catch (IOException e) {
			throw new DhtException(e.getMessage(), e);
		}
	}

	@Override
	public void run() {
		while (true) {
			Socket socket = null;
			SocketHandler socketHandler = null;
			try {
				socket = serverSocket.accept();
			} catch (IOException e) {
				continue;
			}
			socketHandler = new SocketHandler(localInfo, socket);
			synchronized (socketQueue) {
				socketQueue.add(socketHandler);
				socketQueue.notify();
			}
		}
	}
}
